package com.scanner.ocr.abbyy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AbbyClient {

	@Autowired
	private AbbyyService abbyService;

	public String processTextRecognition(byte[] fileContent) throws Exception{
		String language = "English";

		ProcessingSettings.OutputFormat outputFormat = ProcessingSettings.OutputFormat.txt;

		ProcessingSettings settings = new ProcessingSettings();
		settings.setLanguage(language);
		settings.setOutputFormat(outputFormat);
		
		System.out.println("Before processing image");
		Task task = abbyService.processImage(fileContent, settings);

		return waitAndDownloadResult(task);

	}
	
	/**
	 * Wait until task processing finishes and download result.
	 */
	private String waitAndDownloadResult(Task task)
			throws Exception {
		task = waitForCompletion(task);
		String result = null;
		if (task.Status == Task.TaskStatus.Completed) {
			System.out.println("Downloading..");
			result = abbyService.downloadResult(task);
			System.out.println("Extracted text "+result);
		} else if (task.Status == Task.TaskStatus.NotEnoughCredits) {
			System.out.println("Not enough credits to process document. "
					+ "Please add more pages to your application's account.");
		} else {
			System.out.println("Task failed");
		}
		return result;

	}
	
	/** 
	 * Wait until task processing finishes
	 */
	private Task waitForCompletion(Task task) throws Exception {
		while (task.isTaskActive()) {
			Thread.sleep(2000);

			System.out.println("Waiting..");
			task = abbyService.getTaskStatus(task.Id);
		}
		return task;
	}
}
